#include "DebugView.h"

using namespace sf;

DebugView::DebugView(sf::RenderWindow* const window, const float physicsViewFactor, const float lineWidth): 
window(window),
physicsViewFactor(physicsViewFactor),
lineWidth(lineWidth)
{
}

void DebugView::DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color)
{
	Shape polygon;
	for (int32 i = 0; i < vertexCount; ++i)	{
		polygon.AddPoint(convertVector(vertices[i]), convertColor(color));;
	}
	polygon.EnableFill(false);
	polygon.SetOutlineWidth(lineWidth);
	window->Draw(polygon);
}

void DebugView::DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color)
{
	Shape polygon;
	for (int32 i = 0; i < vertexCount; ++i)	{
		polygon.AddPoint(convertVector(vertices[i]), convertColor(color));;
	}
	window->Draw(polygon);
}

void DebugView::DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color)
{
	window->Draw(Shape::Circle(convertVector(center), radius * physicsViewFactor, Color(0,0,0,0), lineWidth, convertColor(color)));
}

void DebugView::DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color)
{
	Vector2f sfCenter = convertVector(center);
	//Unit vector, no convertion needed
	Vector2f sfAxis = Vector2f(axis.x, -axis.y);
	float sfRadius = radius * physicsViewFactor;
	window->Draw(Shape::Circle(sfCenter, sfRadius, convertColor(color)));
	window->Draw(Shape::Line(sfCenter, sfAxis * sfRadius + sfCenter, lineWidth, Color::Black, lineWidth, Color::Black));
}

void DebugView::DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color)
{
	window->Draw(Shape::Line(convertVector(p1), convertVector(p2), lineWidth, convertColor(color), lineWidth, convertColor(color)));
}

void DebugView::DrawXForm(const b2XForm& xf)
{
	/*
	b2Vec2 p1 = xf.position, p2;
	const float32 k_axisScale = 0.4f;
	glBegin(GL_LINES);
	
	glColor3f(1.0f, 0.0f, 0.0f);
	glVertex2f(p1.x, p1.y);
	p2 = p1 + k_axisScale * xf.R.col1;
	glVertex2f(p2.x, p2.y);

	glColor3f(0.0f, 1.0f, 0.0f);
	glVertex2f(p1.x, p1.y);
	p2 = p1 + k_axisScale * xf.R.col2;
	glVertex2f(p2.x, p2.y);

	glEnd();
	*/
}

Color DebugView::convertColor(const b2Color& color)
{
	return sf::Color(
		static_cast<sf::Uint8>(color.r * 255),
		static_cast<sf::Uint8>(color.g * 255), 
		static_cast<sf::Uint8>(color.b * 255));
}

Vector2f DebugView::convertVector(const b2Vec2& vector)
{
	return Vector2f(vector.x * physicsViewFactor, vector.y * -physicsViewFactor);
}
